export interface TextPolishResponse {
  data: {
    success?: boolean
    polished_text?: string
    error?: string
    configs?: string[]
    default_config?: string
    config?: TextPolishConfig
  }
}

export interface TextPolishConfig {
  style: string
  filters: string[]
  perspective: string
  length_ratio: number
}

export interface TextPolishParams {
  text: string
  style?: string
  filters?: string[]
  perspective?: string
  length_ratio?: number
  config_name?: string
}

export interface StreamResponse {
  content: string
  done: boolean
  error?: string
}

export const textPolishApi = {
  async polishTextWithAI(text: string, model: string, prompt?: string): Promise<{
    promise: Promise<void>,
    abort: () => void
  }> {
    const url = '/api/chat_storyboard'

    // 使用传入的润色提示，如果没有则使用默认提示
    let polishPrompt = prompt ? `${prompt}` : '帮我对以下文字进行润色改文，以第一人称讲述故事，去掉血腥黄色镜头，以抖音短视频爆款开头：\n\n'

    // 创建 AbortController 用于取消请求
    const controller = new AbortController()
    const signal = controller.signal

    // 存储文本块，用于分段处理
    let textSegments: string[] = []
    let currentSegmentIndex = 0

    // 将长文本分段
    const MAX_LENGTH = 2000
    if (text.length > MAX_LENGTH) {
      let start = 0
      while (start < text.length) {
        let end = start + MAX_LENGTH
        // 尝试在句子或段落结束处分段
        if (end < text.length) {
          const possibleBreaks = ['，', '!', '”']
          for (let i = 0; i < 100; i++) { // 向前查找最多100个字符
            if (end - i <= start) break
            if (possibleBreaks.includes(text[end - i])) {
              end = end - i + 1 // 包含标点符号
              break
            }
          }
        } else {
          end = text.length
        }
        textSegments.push(text.substring(start, end))
        start = end
      }
    } else {
      textSegments = [text]
    }

    // 返回包含promise和abort方法的对象
    return {
      promise: processSegments(),
      abort: () => controller.abort()
    }

    // 处理所有文本段落的函数
    async function processSegments(): Promise<void> {
      try {
        let replaced = '2000'
        for (let i = 0; i < textSegments.length; i++) {
          currentSegmentIndex = i
          const segment = textSegments[i]
          const isLastSegment = i === textSegments.length - 1
          if (i !== 0) {
            const paragraphLength = (Math.ceil(segment.length / 10) * 10).toString()
            polishPrompt = polishPrompt.replace(replaced, paragraphLength)
            polishPrompt = '继续按照这个模板继续润色：' + polishPrompt
            replaced = paragraphLength
          }
          const segmentPrompt = polishPrompt + segment

          // 使用fetch API发送请求并处理流式响应
          const response = await fetch(url, {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
              message: segmentPrompt,
              model: model
            }),
            signal // 添加AbortController的signal用于取消请求
          })

          if (!response.ok || !response.body) {
            throw new Error('请求失败')
          }

          // 处理流式响应
          const reader = response.body.getReader()
          const decoder = new TextDecoder()

          let buffer = '' // 用于存储未完整解析的流数据

          // 在每个段落开始时发送段落开始标记
          window.dispatchEvent(new CustomEvent('text-polish-segment-start', {
            detail: {
              segmentIndex: currentSegmentIndex,
              totalSegments: textSegments.length
            }
          }))

          while (true) {
            const { done, value } = await reader.read()
            if (done) break

            buffer += decoder.decode(value, { stream: true })

            // 拆分 SSE 数据
            const parts = buffer.split('\n\n')

            for (let j = 0; j < parts.length - 1; j++) {
              const line = parts[j].trim()
              if (line.startsWith('data: ')) {
                try {
                  const jsonStr = line.substring(6).trim() // 去掉 `data: ` 前缀
                  const jsonData = JSON.parse(jsonStr) // 解析 JSON

                  if (jsonData.error) {
                    // 抛出错误时包含段落索引信息
                    const error = new Error(jsonData.error)
                    // @ts-ignore 添加自定义属性
                    error.segmentIndex = currentSegmentIndex
                    throw error
                  }

                  if (!jsonData.done) {
                    // 触发内容更新回调
                    window.dispatchEvent(new CustomEvent('text-polish-update', {
                      detail: {
                        content: jsonData.content,
                        segmentIndex: currentSegmentIndex,
                        totalSegments: textSegments.length
                      }
                    }))
                  }
                } catch (e) {
                  console.error('解析响应数据失败:', e)
                  throw e
                }
              }
            }

            // 只保留最后一个未完整的部分
            buffer = parts[parts.length - 1]
          }

          // 如果有多个段落，在段落之间添加分隔符
          if (!isLastSegment) {
            window.dispatchEvent(new CustomEvent('text-polish-segment-complete', {
              detail: {
                segmentIndex: currentSegmentIndex,
                isLastSegment: false,
                segmentText: textSegments[currentSegmentIndex]
              }
            }))
          }
        }

        // 所有段落处理完成
        window.dispatchEvent(new CustomEvent('text-polish-complete', {
          detail: {
            success: true,
            segments: textSegments
          }
        }))
      } catch (error) {
        // 处理错误
        window.dispatchEvent(new CustomEvent('text-polish-error', {
          detail: {
            error: error instanceof Error ? error.message : '未知错误',
            // @ts-ignore 获取自定义属性
            segmentIndex: error instanceof Error && error.segmentIndex !== undefined ? error.segmentIndex : undefined
          }
        }))
      }
    }
  }
}
